Certificates = new Meteor.Collection('certificates');

DefaultCertificate = function(){
  var new_line = "\r"
      , default_certificate = {
          logo_file: "corpedia-logo.png"
        , company_name: "Known Company"
        , course_name: "Known Course Name"
        , student_name: "Known Name"
        , instructions: "Please print and sign for your records."
        , sign: "Sign"
        , date: "Date"
        , print: "Print"
        , print_message: "For best results, set printer to landscape orientation."
        , certificate_markup: "<div id='certificate'>" + new_line +
            "  <img src='./images/{{logo_file}}' alt='{{company_name}} logo' />" + new_line +
            "  <h1><strong>{{company_name}} {{course_name}}</strong></h1>" + new_line +
            "  <h2>This is to certify that <strong>{{student_name}}</strong> has completed <strong>{{course_name}}</strong></h2>" + new_line +
            "  <p>Please sign and print for your records.</p>" + new_line +
            "  <div id='signature'>" + new_line +
            "    <p>{{sign}}</p>" + new_line +
            "    <p>{{date}}</p>" + new_line +
            "  </div>" + new_line +
            "</div>"
        , instructions_markup: "<div id='instructions'>" +  new_line +
            " <button onclick='window.print()'>Print</button>" + new_line +
            " <p>{{print_message}}</p>" + new_line +
            "</div>"
        , certificate_rendered: function(){
            return Template.CertificatePreview(this);
          }
      };
  
  return default_certificate;
};

if (Meteor.is_client) {
  
  Template.Navbar.events = {
    
    // Brand
    'click a.brand': function(e){
      e.preventDefault();
      router.navigate("/", {trigger: true});
    },
    
    // Certificates Link
    
    'click a.certificates_link': function(e){
      e.preventDefault();
      router.navigate("/certificates", {trigger: true});
    },
    
    
    'keyup input.searcher': function(e){
      var certs;
      
      Session.set('current_query', e.target.value);
      certs = Certificates.find({}, {
        $where: "this.company.indexOf(Session.get('current_query') > -1)"
      }).fetch();
      console.log(certs);
      Session.set('current_query', null);
    }
    
  };
  
  Template.Splash.events = {
    
    'click a.go': function(e){
      e.preventDefault();
      router.navigate("/certificates", {trigger: true});
    }
    
  };
  
  // Make certificates available to the view...
  
  Template.Certificates.certificates = function(){
    return Certificates.find({}, {limit: 5, reactive: false}).fetch();
  };
  
  Template.Certificates.events = {
    
    // New
    
    'click a.new': function(e){
      e.preventDefault();
      Session.set("new_certificate", true);
      router.navigate("certificate/new", {trigger: true});
    }
  };
  
  Template.certificate_list_item_view.events = {
    
    // Preview
    
    'click a.preview': function(e){
      e.preventDefault();
      
      Session.set('current_certificate', this);
      
      Certificates.update(
        {id: this._id},
        this, 
        function(){
          router.navigate('preview/' + this._id, {trigger: true});
        }.bind(this)
      );
    },
    
    // Edit
    
    'click a.edit': function(e){
      e.preventDefault();
      Session.set("current_certificate", this);
      router.navigate("certificate/" + this._id, {trigger: true});
    },
    
    // Remove
    
    'click a.remove': function(e){
      e.preventDefault();
      Session.set("current_certificate", this);
      Template.makeRemoveModal(this.title, 'certificate', 'certificate_list_item_view');
    },
    
    // Remove Exposed (for modal)
    
    remove: function(){
      Certificates.remove(Session.get("current_certificate"));
    }
    
  };
  
  Template.certificate_form_view.events = {
    
    // Cancel
    
    'click a.cancel': function(e){
      e.preventDefault();
      
      if(Session.get("new_certificate")){
        Certificates.remove(Session.get("current_certificate"));
      }
      
      Session.set("new_certificate", false);
      Session.set("current_certificate", null);
      
      console.log(Session.get('cert_editor'));
      
      router.navigate("/", {trigger: true});
    },
    
    // Save
    
    'click a.save': function(e){
      e.preventDefault();
      var props = {};
      
      $('#certificate_form').find('input.span10').each(function(i, prop){
        props[prop.name] = prop.value;
      });
      
      props.certificate_markup = Session.get('cert_editor').getSession().getDocument().getValue();
      props.instructions_markup = Session.get('inst_editor').getSession().getDocument().getValue();
      
      Certificates.update(Session.get("current_certificate"), props, function(){
        router.navigate("/certificates", {trigger: true});
      });
    }
    
  };
  
  openWindow = function(url){
    console.log("openWindow", url);
    var win = window.open(url, "certMasterPreview");
    return win;
  };

}

if (Meteor.is_server) {
  
  if (Certificates.find().count() === 0) {

    Certificates.insert(new DefaultCertificate());
  
    _(19).times(function(){
      var certificate = new DefaultCertificate();
      certificate.company_name = Faker.Company.companyName();
      certificate.course_name = Faker.Company.catchPhrase();
      certificate.name = Faker.Name.findName();
    
      Certificates.insert(certificate);
    });
  
  }
  
}
